<?php

namespace app\index\controller\wanlshop;

use app\common\Codes;
use app\index\model\wanlshop\Auth;
use think\Controller;
use think\Db;
use think\Exception;
use think\Validate;

class ShopApi extends Controller
{


    public function shopinfo(){
        $data = (new Auth())->where('user_id',input('user_id'))->find();
        return Codes::success('',$data);
    }

    public function add_info(){
        $post = request()->post();
        $post['verify'] = 2;
        $post['name'] = $post['shopname'];
        $rule = [
            'username'  => 'require|length:3,30',
            'password'  => 'require|length:6,30',
            'email'     => 'require|email',
            'mobile'    => 'regex:/^1\d{10}$/',
        ];

        $msg = [
            'username.require' => 'Username can not be empty',
            'username.length'  => 'Username must be 3 to 30 characters',
            'password.require' => 'Password can not be empty',
            'password.length'  => 'Password must be 6 to 30 characters',
            'email'            => 'Email is incorrect',
            'mobile'           => 'Mobile is incorrect',
        ];
        $password = $post['mobile'].'...';
        $data = [
            'username'  => $post['mobile'],
            'password'  => $password,
            'email'     => $post['email'],
            'mobile'    => $post['mobile'],
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (!$result) {
            return Codes::error($validate->getError());
        }

        $resMsg = \app\common\library\Auth::instance()->checkData($data['username'],$data['password'],$data['email'],$data['username']);
        if($resMsg !== true){
            return Codes::error($resMsg);
        }



        $user_id = $post['user_id'];
        Db::startTrans();
        try {
            $entry = (new \app\index\model\wanlshop\Auth())->where(['user_id' => $user_id])->find();
            if($entry){
              $entry ->allowField(true)->save($post);
            }else{
                $post['user_id'] = $user_id;
             (new \app\index\model\wanlshop\Auth()) ->allowField(true)->save($post);
            }

            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            return Codes::error($exception->getMessage());
        }
        return Codes::success('success',[
            'password'=>$password
        ]);
    }
}